<!--
 * @Author: zhuxiaoyi
 * @Date: 2024-01-09 10:50:36
 * @LastEditor: zhuxiaoyi
 * @LastEditTime: 2024-07-04 11:46:07
 * @Description: 
-->
<template>
    <el-row>
        <el-col :span="24" style="display: flex;justify-content:flex-end;position: relative;">
            <div style="position: absolute;z-index: 100;right: 0;top: 10px;">
                <el-card v-show="false" id="popup" class="ol-popup" style="width: 200px" shadow="always">
                    <template #header>
                        <div id="popup-header" class="popup-header">
                            <span>图斑编辑</span>
                            <el-button link class="button" :icon="Close"></el-button>
                        </div>
                    </template>
                    <el-radio-group v-model="classValue" class="ml-4">
                        <el-radio :border="true" value="1" label="非水体" size="small"></el-radio>
                        <el-radio :border="true" value="2" label="水体" size="small"></el-radio>
                    </el-radio-group>
                </el-card>
            </div>


        </el-col>
    </el-row>
    <div style="position: relative;">
        <el-card v-show="editBoard" style="max-width: 480px" class="edit-container">
            <div class="tool-header">
                <!-- <span>工具栏</span> -->
                <div style="display:flex;align-item:center;">
                    <span>当前模式:</span> &nbsp;<el-link style="font-size: 12px;" @click="chanEditStatusHandler"
                        :type="editStatus ? 'success' : 'warning'">{{
                            editStatus ? '编辑模式' :
                                "预览模式"
                        }}</el-link>
                </div>
                <!--  <el-button :type="editStatus ? 'primary' : 'success'" @click="chanEditStatusHandler" size="small"
                    plain>{{
                        editStatus ? '退出编辑' : '开始编辑' }} </el-button> -->
            </div>
            <div class="tool-body">
                <el-avatar @click="chanEditStatusHandler" shape="square" :size="30" title="成果编辑"
                    style="background-color: #212f3d;cursor: pointer;" :src="editStatus ? editIcon2 : editIcon1" />
                <el-avatar shape="square" :size="30" style="background-color: #18222C; cursor: pointer;" title="底图选择"
                    @click="popoverVisible = !popoverVisible" :src="popoverVisible ? mapIcon2 : mapIcon1" />
                <el-avatar shape="square" :size="30" style="background-color: #18222C; cursor: pointer;" title="矢量导出"
                    @click="downloadHandler" :src="downloading ? export2 : export1" />
                <el-collapse-transition>
                    <el-card v-show="popoverVisible" class="base-layer-card" size="small">
                        <template #header>
                            <div class="base-layer-header">
                                <span>底图选择</span>
                                <el-button link class="button" @click="popoverVisible = false"
                                    :icon="Close"></el-button>
                            </div>
                        </template>
                        <div class="base-layer-container">
                            <el-card v-for="layer in baseLayers" :key="layer.type" :body-style="{ padding: '0px' }"
                                style="width:74px;cursor: pointer;" class="img-card"
                                @click="baseImageClickHandler(layer)">
                                <el-image style="width: 74px; height: 54px" :src="layer.img" :fit="'fill'" />
                                <div style="padding: 5px">
                                    <span>{{ layer.name }}</span>
                                </div>
                            </el-card>
                        </div>
                        <template #footer>
                            <el-row>
                                <el-col style="display: flex; justify-content:space-between">
                                    矢量图层
                                    <el-switch v-model="resultLayerVisible" @change="switchChangeHandler" />
                                </el-col>
                            </el-row>
                        </template>
                    </el-card>
                </el-collapse-transition>
            </div>
            <div class="tool-footer">
                <div style="font-size: 10px;width: 160px;word-break: break-all;">影像名称：{{ currentShpName }}</div>
                <el-button type="primary" size="small" @click="pushResult" :loading="pushLoading">成果推送</el-button>
            </div>

        </el-card>
        <el-card v-show="selectedFeatures.length > 0" class="selected-card">
            当前选中图斑数量 &nbsp;<el-link type="primary">{{ selectedFeatures.length }}&nbsp;</el-link> 条
            <el-row>
                <el-col :span="24" style="display: flex;justify-content:center;margin-top: 20px;">
                    <el-button type="primary" @click="editFeatures('1')">非水体</el-button>
                    <el-button type="primary" @click="editFeatures('2')">水体</el-button>
                </el-col>
            </el-row>
        </el-card>
        <div class="task-card" v-show="showCard" style="width:400px">
            <div style="color: #fff;font-size:16px;padding-bottom: 10px;cursor: pointer;" @click="showCard = false">
                条件查询
            </div>
            <el-form :label-position="'left'" label-width="70px" :model="formLabelAlign" class="filter-container">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="卫星类型">
                            <el-select v-model="satType" class="m-2" placeholder="Select" size="small"
                                style="width: 305px">
                                <el-option v-for="item in options" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="处理状态">
                            <el-select v-model="satType" class="m-2" placeholder="Select" size="small"
                                style="width: 305px">
                                <el-option v-for="item in options" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="开始时间">
                            <el-date-picker v-model="startTime" type="datetimerange" start-placeholder="开始日期"
                                end-placeholder="结束日期" class="input-box" :size="'small'" style="width: 306px" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="19">
                        <el-form-item label="影像名称">
                            <el-input v-model="satType" style="width: 305px" :size="'small'"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-button type="primary" size="small"
                            style="margin: 5px;width: calc(100% - 5px); ">查询</el-button>
                    </el-col>
                </el-row>
            </el-form>
            <el-row style="margin-top:10px">
                <el-col :span="24">
                    <el-table :data="tableData" style="width: 100%" size="small" :border="true" height="430">
                        <el-table-column :align="'center'" type="index" label="序号" />
                        <el-table-column :align="'center'" prop="name" label="名称" show-overflow-tooltip />
                        <el-table-column :align="'center'" prop="satType" label="卫星类型" width="100px"
                            show-overflow-tooltip />
                        <el-table-column type="expand" label="详情">
                            <template #default="props">
                                <ul class="detial-con">
                                    <li>处理日期: &nbsp; {{ props.row.date }}</li>
                                    <li>影像名称: &nbsp; {{ props.row.name }}</li>
                                    <li>卫星类型: &nbsp; {{ props.row.satType }}</li>
                                    <li>处理状态: &nbsp; <el-tag type="success" size="small">{{ props.row.state }}</el-tag>
                                    </li>
                                </ul>
                            </template>
                        </el-table-column>
                        <el-table-column :align="'center'" label="操作" width="60px">
                            <template #default>
                                <el-button link type="primary" size="small">推送</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
                <el-col :span="24" style="padding:5px;overflow: auto;" class="page-container">
                    <pagination-custom :pagination="taskPagination" @handleSizeChange=""
                        @handleCurrentChange=""></pagination-custom>
                </el-col>
            </el-row>
        </div>
        <div class="task-card" v-show="!showCard" style="width:400px">
            <div style="color: #fff;font-size:16px;padding-bottom: 10px;cursor: pointer;" @click="showCard = true">
                多源遥感数据洪涝灾害应急监测系统
            </div>
            <el-col :span="24">
                <el-form-item label="湖库地区">
                    <el-select v-model="currentLocation" class="m-2" placeholder="请选择湖库地区" size="small"
                        style="width: 305px" @change="locationChangeHandler" clearable>
                        <el-option v-for="item in locationOptions" :key="item.value" :label="item.label"
                            :value="item.value" />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-tree v-loading="treeLoading" style="max-width: 600px" :data="taskTree" :props="defaultProps"
                :default-expanded-keys="[5]">
                <template #default="{ node, data }">
                    <div class="custom-tree-node">
                        <div v-if="!node.isLeaf"> {{ node.label }}</div>
                        <div v-if="node.isLeaf" @click="handleNodeClick(data)" style="display: flex;">

                            <el-tag :type="filterLabelStatus(data.status)" size="small" style="margin-right: 5px;">
                                {{ filterStatus(data.status) }}</el-tag>
                            <p class="file-name" :title="data.fileName">{{ data.fileName }}</p>
                            <el-popconfirm title="确定要删除当前任务么?" @confirm="deleteTask(data)">
                                <template #reference>
                                    <el-link type="danger" @click.stop="">删除</el-link>
                                </template>
                            </el-popconfirm>
                        </div>
                    </div>
                </template>
            </el-tree>
        </div>
    </div>
    <div id="map-container" :style="`height:${view.height}px`" @click="popoverVisible = false"></div>
    <div>
        <div id="mouse-position" class="position_coordinate"></div>
    </div>
</template>
<script setup lang="ts">
import { defineComponent, reactive, ref, toRefs, onMounted, watch } from "vue";
import paginationCustom from "@/components/pagination/paginationCustom.vue";
import axios from "axios";
import HttpService from "@/api/api";
import { Close, Edit } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import { Map, View } from 'ol'
import { Style, Fill, Stroke } from 'ol/style'
import { Tile as TileLayer, Image } from 'ol/layer'
import { get, fromLonLat } from 'ol/proj';
import { getWidth, getTopLeft, boundingExtent } from 'ol/extent'
import { WMTS, TileWMS, OSM, Tile, ImageWMS, TileImage } from 'ol/source'
import MousePosition from "ol/control/MousePosition";
import { format as formatAxirs } from 'ol/coordinate';
import { WFS, GeoJSON } from 'ol/format';
import WMTSTileGrid from 'ol/tilegrid/WMTS'
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector';
import { DragBox, Select } from 'ol/interaction';
import { singleClick, click, platformModifierKeyOnly } from 'ol/events/condition';
import 'ol/ol.css'; // 导入 OpenLayers 样式文件
import baseImg1 from '@/assets/img/vec.jpg'
import baseImg2 from '@/assets/img/img.jpg'
import baseImg3 from '@/assets/img/ter.jpg'
import mapIcon2 from '@/assets/img/map2.png'
import mapIcon1 from '@/assets/img/map1.png'
import editIcon1 from '@/assets/img/edit1.png'
import editIcon2 from '@/assets/img/edit2.png'
import export1 from '@/assets/img/export1.png'
import export2 from '@/assets/img/export2.png'

import { ElLoading } from 'element-plus'
var view = reactive({
    height: window.innerHeight,
});
// const geoserverBaseURL = 'http://192.168.107.224:8055'
const geoserverBaseURL = 'http://123.57.240.141:8055'
// const geoserverBaseURL = 'http://localhost:8055'
const showCard = ref(false)
const resultLayerVisible = ref(true)
const popoverVisible = ref(false)
const downloading = ref(false)
const router = useRouter()
const projection = get("EPSG:4326");
const projectionExtent = projection.getExtent();
const size = getWidth(projectionExtent) / 256;
const startTime = ref('')
const resolutions = [];
const editBoard = ref(true);
const currentShpName = ref('origin')
const currentTaskId = ref(null)
const pushLoading = ref(false)
const editStatus = ref(false)
const classValue = ref('1')
const currentLocation = ref('水体1')
const locationRecord = ref('水体1')
const selectedFeatures = reactive([]);
const handleNodeClick = (data) => {
    currentShpName.value = data.fileName
    currentTaskId.value = data.id
    map && map.getLayers().forEach(layer => {
        if (layer.values_.name == 'resultLayer' || layer.values_.name == 'baseLayer') {
            layer.getSource().refresh()
        }
    });
    const mapView = map.getView()
    const gisInfo = JSON.parse(data.gisInfo)
    if (locationRecord.value !== data.location) {
        mapView.fit(gisInfo, {
            constrainResolution: false // 可选，设置是否约束地图视图的分辨率
        });
    }
    locationRecord.value = data.location
    changeLayer()
}
function changeLayer() {
    selectedFeatures.length = 0
    var newLayer = new TileLayer({ // 新的 WMS 图层 
        source: new TileWMS({
            url: geoserverBaseURL + '/geoserver/result/wms', // GeoServer的WMS服务URL
            params: {
                'LAYERS': 'result:' + currentShpName.value,
                'VERSION': '1.1.0',
                'FORMAT': 'image/png8', // 图像格式为 PNG
            },
            serverType: 'geoserver'
        })
    });
    newLayer.set('name', "baseLayer")
    map.getLayers().setAt(4, newLayer); // 替换第二个图层（索引为 1）
}


const deleteTask = function (task) {
    let params = {
        id: task.id
    };
    HttpService.taskManage.deleteTask(
        params,
        (res) => {

            if (res.status == 200) {
                ElMessage({
                    message: "删除成功 ",
                    type: "success",
                });
                getTreeTasks()
            } else {
                ElMessage({
                    message: res,
                    type: "error",
                });
            }
        },
        (error) => {
            console.log(error);
        }
    );
}


const taskTree = ref([])
const treeLoading = ref(false)
const defaultProps = {
    children: 'children',
    label: 'label',
}
const baseLayers = [
    {
        type: "vecLayer",
        name: "矢量底图",
        img: baseImg1
    },
    {
        type: 'imgLayer',
        name: "影像底图",
        img: baseImg2
    },
    {
        type: 'terLayer',
        name: "地形晕渲",
        img: baseImg3
    }
]

const tableData = [
    {
        date: '20220909',
        name: 'S2B T52TET 20220909T021539 N0400 RO03',
        state: '待编辑',
        satType: 'S2X_MSI',
    },
    {
        date: '20220909',
        name: 'S2B T52TET 20220909T021539 N0400 RO03',
        state: '待编辑',
        satType: 'S2X_MSI',
    },
    {
        date: '20220909',
        name: 'S2B T52TET 20220909T021539 N0400 RO03',
        state: '待编辑',
        satType: 'S2X_MSI',
    },
    {
        date: '20220909',
        name: 'S2B T52TET 20220909T021539 N0400 RO03',
        state: '待编辑',
        satType: 'S2X_MSI',
    },
    {
        date: '20220909',
        name: 'S2B T52TET 20220909T021539 N0400 RO03',
        state: '待编辑',
        satType: 'S2X_MSI',
    },
    {
        date: '20220909',
        name: 'S2B T52TET 20220909T021539 N0400 RO03',
        state: '待编辑',
        satType: 'S2X_MSI',
    },

    {
        date: '20220909',
        name: 'S2B T52TET 20220909T021539 N0400 RO03',
        state: '待编辑',
        satType: 'S2X_MSI',
    },
    {
        date: '20220909',
        name: 'S2B T52TET 20220909T021539 N0400 RO03',
        state: '待编辑',
        satType: 'S2X_MSI',
    },
]

const satType = ref('')

const options = [
    {
        value: 'Option1',
        label: 'Option1',
    },
    {
        value: 'Option2',
        label: 'Option2',
    },
    {
        value: 'Option3',
        label: 'Option3',
    },
    {
        value: 'Option4',
        label: 'Option4',
    },
    {
        value: 'Option5',
        label: 'Option5',
    },
]

const locationOptions = [
    {
        value: '水体1',
        label: '水体1',
    },
    {
        value: '班戈错',
        label: '班戈错',
    },
    {
        value: '错鄂',
        label: '错鄂',
    },
    {
        value: '水体1岸线监测范围',
        label: '水体1岸线监测范围',
    },
]
let map;
for (let z = 2; z < 19; ++z) {
    resolutions[z] = size / Math.pow(2, z);
}

let taskPagination = reactive({
    page_index: 1,
    page_size: 100,
    page_total: 301,
});
onMounted(() => {
    initMap()
});
// 切换底图函数


const getTreeTasks = function () {
    let params = {
        location: currentLocation.value
    };
    treeLoading.value = true
    let a = { id: 4, label: "暂无数据", children: [] }
    taskTree.value = [a]
    HttpService.taskManage.getTreeTasks(
        params,
        (res) => {

            if (res.status == 200) {
                res.data.data.forEach(item => {
                    taskTree.value.push(item)
                })
                taskTree.value.splice(0, 1)
            } else {
                console.log("获取信息失败" + res);
            }
            treeLoading.value = false
        },
        (error) => {
            console.log(error);
            treeLoading.value = false
        }
    );
}
getTreeTasks()

const baseImageClickHandler = function (layer) {
    switchBaseLayer(layer.type)
}
const switchBaseLayer = (layerType) => {
    if (!map) return; // 如果地图对象不存在，则返回
    map.getLayers().forEach(layer => {
        if (layer.values_.name == layerType || layer.values_.name == 'imgLayer' || layer.values_.name == 'resultLayer' || layer.values_.name == 'baseLayer') {
            layer.setVisible(true)
        } else {
            layer.setVisible(false)
        }
    });
}
const switchChangeHandler = function () {
    changeLayerVisible('resultLayer', resultLayerVisible.value)
}
const changeLayerVisible = function (layerName, visible) {
    map && map.getLayers().forEach(layer => {
        if (layer.values_.name == layerName) {
            layer.setVisible(visible)
        }
    });
}

const initMap = function () {
    const TIANDI_KEY = 'eec7fae87888db2dc4c30c0c458fb66b'
    // const center = ref([116.41124529391394, 39.953530444730816]);
    // const center = ref([103.160298, 26.253992]);
    const center = ref([89.09, 31.93]);
    // c: 经纬度投影 w: 球面墨卡托投影
    const matrixSet = 'c'
    // let layerName = '53011303042R_LC08_L1TP_NDVI_FV2'
    // let layerName= 'GF1D_PMS_E89.2_N31.9_20231228_L1A1257344264-MUX_ortho'
    const wfsSource = new VectorSource({
        format: new GeoJSON(),
        url: function (extent) {
            return (
                geoserverBaseURL + '/geoserver/result/ows?service=WFS&' +
                `version=1.0.0&request=GetFeature&typeName=result:${currentShpName.value}_shp&` +
                'outputFormat=application/json&srsname=EPSG:4326&' +
                'bbox=' + extent.join(',') + ',EPSG:3857'
            );
        },
    });

    let vectorLayer = new VectorLayer({
        source: wfsSource,
        style: function (feature) {
            let classValue = feature.get('class');
            var color = '';
            if (classValue == '2') {
                // color = '#68A7C4';
                // color = '#ABC6EF';
                color = 'rgba(0, 0, 170, 0.6)';
            } else if (classValue == '1') {
                // color = '#EEEEEE';
                color = 'rgba(255, 255, 255,0)';
            } else {
                color = 'red'; // 默认颜色
            }
            return new Style({
                fill: new Fill({
                    color: color
                }),
                /*  stroke: new Stroke({
                    color: 'rgb(10,194,58)',
                    width: 1
                 }) */
            });
        }
    });
    vectorLayer.setOpacity(1);
    vectorLayer.set('name', "resultLayer")

    const wmsLayers = new TileLayer({
        source: new TileWMS({
            url: geoserverBaseURL + '/geoserver/result/wms', // GeoServer的WMS服务URL
            params: {
                'LAYERS': 'result:' + currentShpName.value, // 要显示的图层的工作空间和名称,'FORMAT': 'image/png', // 图片格式
                'VERSION': '1.1.0',
                'FORMAT': 'image/png8', // 图像格式为 PNG
            },
            serverType: 'geoserver'
        })
    })
    wmsLayers.set('name', "baseLayer")
    wmsLayers.setOpacity(1);

    const terLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'ter'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'ter',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                //resolutions: res.slice(0, 15),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })
    terLayer.set('name', "terLayer")

    const imgLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'img'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'img',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                //resolutions: res.slice(0, 15),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })
    imgLayer.set('name', "imgLayer")

    const vecLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'vec'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'vec',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                //resolutions: res.slice(0, 15),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })

    vecLayer.set('name', "vecLayer")

    const cvaLayer = new TileLayer({
        source: new WMTS({
            url: `http://t{0-6}.tianditu.com/${'cva'}_${matrixSet}/wmts?tk=${TIANDI_KEY}`,
            layer: 'cva',
            matrixSet: matrixSet,
            style: "default",
            crossOrigin: 'anonymous', // 解决跨域问题 如无该需求可不添加
            format: "tiles",
            wrapX: true,
            tileGrid: new WMTSTileGrid({
                origin: getTopLeft(projectionExtent),
                resolutions: resolutions,
                matrixIds: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14']
            })
        })
    })
    cvaLayer.set('name', "cvaLayer")

    map = new Map({
        target: 'map-container',
        layers: [
            // 底图
            imgLayer,
            terLayer,
            vecLayer,
            cvaLayer,
            wmsLayers,
            vectorLayer,
        ],
        view: new View({
            projection: projection,
        })
    })
    // 创建一个包含四个角点的Extent对象
    var extent = [88.381872, 31.482, 89.3952, 32.160239999999995];

    map.getView().fit(extent, {
        constrainResolution: false // 可选，设置是否约束地图视图的分辨率
    });



    const dragBox = new DragBox({
        condition: platformModifierKeyOnly,
    });

    map.addInteraction(dragBox);
    dragBox.on('boxend', function () {
        let extent = dragBox.getGeometry().getExtent();
        editStatus.value && wfsSource.forEachFeatureIntersectingExtent(
            extent,
            (feature) => {
                let featureIndex = selectedFeatures.indexOf(feature)
                if (featureIndex > -1) {
                    feature.setStyle(undefined)
                    selectedFeatures.splice(featureIndex, 1)
                } else {
                    selectedFeatures.push(feature)
                    // 自定义选中要素的样式，保留填充色
                    let classValue = feature.get('class');
                    var color = '';
                    if (classValue == '2') {
                        color = '#67c23a';
                    } else if (classValue == '1') {
                        color = '#CEEAD6';
                    } else {
                        color = 'rgba(255, 255, 255,0.1)'; // 默认颜色
                    }
                    feature.setStyle(new Style({
                        fill: new Fill({
                            color: color // 自定义填充色
                        }),
                        stroke: new Stroke({
                            color: '#000', // 自定义边框颜色
                            width: 2 // 自定义边框宽度
                        })
                    }))
                }
            }
        );
    });

    // clear selection when drawing a new box and when clicking on the map
    dragBox.on('boxstart', function () {
    });



    var mousePositionControl = new MousePosition({
        coordinateFormat: function (coordinate) {
            return formatAxirs(coordinate, '经度:{x} 纬度:{y}', 2);
        },
        projection: 'EPSG:4326',
        className: "custom-mouse-position",
        target: document.getElementById("mouse-position"), //将位置数据放到那里
    });
    map.addControl(mousePositionControl);


    map.on('singleclick', function (e) {
        editStatus.value && map.forEachFeatureAtPixel(e.pixel, function (feature) {
            let featureIndex = selectedFeatures.indexOf(feature)
            if (featureIndex > -1) {
                feature.setStyle(undefined)
                selectedFeatures.splice(featureIndex, 1)
            } else {
                let classValue = feature.get('class');
                var color = '';
                if (classValue == '2') {
                    color = '#67c23a';
                } else if (classValue == '1') {
                    color = '#CEEAD6';
                } else {
                    color = 'rgba(255, 255, 255,0.1)'; // 默认颜色
                }
                feature.setStyle(new Style({
                    fill: new Fill({
                        color: color // 自定义填充色
                    }),
                    stroke: new Stroke({
                        color: '#000', // 自定义边框颜色
                        width: 2 // 自定义边框宽度
                    })
                }))
                selectedFeatures.push(feature)
            }
            console.log(selectedFeatures)
            console.log(selectedFeatures.length)
            /*  console.log(selectedFeatures)
                const selIndex = selectedFeatures.indexOf(f);
                if (selIndex < 0) {
                    selectedFeatures.push(f);
                    f.setStyle();
                } else {
                    selectedFeatures.splice(selIndex, 1);
                    f.setStyle(undefined);
                } */
        });

        // status.innerHTML = '&nbsp;' + selected.length + ' selected features';
    });

}


const filterStatus = function (status) {
    let statusCN
    switch (status) {
        case 4:
            statusCN = '可编辑'
            break;
        case 5:
            statusCN = '已编辑'
            break;
        case 6:
            statusCN = '已推送'
            break;
        default:
            break;
    }
    return statusCN
}
const filterLabelStatus = function (status) {
    let Label
    switch (status) {
        case 4:
            Label = 'warning'
            break;
        case 5:
            Label = 'primary'
            break;
        case 6:
            Label = 'success'
            break;
        default:
            Label = 'primary'
            break;
    }
    return Label
}


const editFeatures = function (classValue) {
    const loading = ElLoading.service({
        lock: true,
        text: '图斑编辑中...',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    editFeature(classValue)
    setTimeout(() => {
        ElMessage({
            message: "图斑属性修改成功 ",
            type: "success",
        });
        map && map.getLayers().forEach(layer => {
            if (layer.values_.name == 'resultLayer') {
                layer.getSource().refresh()
            }
        });
        updateTaskStatus(5)
        loading.close()
        selectedFeatures.length = 0
    }, 500)
}
const editFeature = function (classValue) {
    let ogc = '';
    selectedFeatures.forEach((feature) => {
        ogc += `<ogc:FeatureId fid="${feature.id_}"/>`;
    });
    const wfsTRequest =
        `<wfs:Transaction xmlns:wfs="http://www.opengis.net/wfs" service="WFS" version="1.0.0">
        <wfs:Update typeName="result:${currentShpName.value}_shp">
            <wfs:Property>
            <wfs:Name>${'class'}</wfs:Name>
            <wfs:Value>${classValue}</wfs:Value> <!-- 设置新的属性值 -->
            </wfs:Property>
            <ogc:Filter xmlns:ogc="http://www.opengis.net/ogc">
            ${ogc}
            </ogc:Filter>
        </wfs:Update>
    </wfs:Transaction>`;
    axios.post(geoserverBaseURL + '/geoserver/wfs', wfsTRequest, {
        headers: {
            'Content-Type': 'application/xml'
        }
    })
        .then(response => {
        })
        .catch(error => {
            ElMessage({
                message: "图斑属性修改失败 ",
                type: "error",
            });
            console.error('Error updating feature:', error);
        });

}

const updateTaskStatus = function (status: number) {
    let params = {
        id: currentTaskId.value,
        status
    };
    HttpService.taskManage.updateTaskStatus(
        params,
        (res) => {

            if (res.status == 200) {
                getTreeTasks()
            } else {
                console.log("获取信息失败" + res);
            }
        },
        (error) => {
            console.log(error);
        }
    );
}

const pushResult = function () {
    pushLoading.value = true;
    let params = {
        id: currentTaskId.value,
    };
    HttpService.taskManage.pushResult(
        params,
        (res) => {
            if (res.status == 200) {
                getTreeTasks()
                pushLoading.value = false;
            } else {
                console.log("获取信息失败" + res);
                pushLoading.value = false;
            }
        },
        (error) => {
            console.log(error);
            pushLoading.value = false;
        }
    );
}



const chanEditStatusHandler = function () {
    const loading = ElLoading.service({
        lock: true,
        text: '模式切换中',
        background: 'rgba(0, 0, 0, 0.7)',
    })

    setTimeout(() => {
        map && map.getLayers().forEach(layer => {
            if (layer.values_.name == 'resultLayer') {
                layer.setStyle((feature) => {
                    let classValue = feature.get('class');
                    var color = '';
                    if (classValue == '2') {
                        // color = '#68A7C4';
                        // color = '#ABC6EF';
                        color = 'rgba(0, 0, 170, 0.6)';
                    } else if (classValue == '1') {
                        // color = '#EEEEEE';
                        color = 'rgba(255, 255, 255,0)';
                    } else {
                        color = 'red'; // 默认颜色
                    }
                    return new Style({
                        fill: new Fill({
                            color: color
                        }),
                        stroke: editStatus.value ? new Stroke({
                            color: 'rgb(10,194,58)',
                            width: 1
                        }) : null
                    });
                })
            }
        });
        editStatus.value = !editStatus.value
        if (!editStatus.value) {
            selectedFeatures.forEach(f => {
                f.setStyle(undefined)
            })
            selectedFeatures.length = 0
        }
        loading.close()
    }, 300)

}
const goBack = function () {
    router.push('/index/general/executeManage/executeList')
}
var view = reactive({
    height: window.innerHeight,
});

const formLabelAlign = reactive({
    name: '',
    region: '',
    type: '',
})

const pushReusltHandler = function (data) {
    console.log(data)
}

const locationChangeHandler = function () {
    getTreeTasks()
}
const downloadHandler = async function () {
    downloading.value = true
    try {
        const response = await axios.get(`${geoserverBaseURL}/geoserver/wfs/wfs?service=WFS&version=1.0.0&request=GetFeature&typeName=result:${currentShpName.value}_shp&outputFormat=SHAPE-ZIP`, {
            params: {
            },
            responseType: 'blob' // 确保响应数据是二进制的
        });
        // 创建一个 URL 对象来表示 Blob 数据
        const url = window.URL.createObjectURL(new Blob([(response).data], { type: 'application/zip' }));

        // 创建一个临时的 <a> 元素来触发下载
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', `${currentShpName.value}_shp.zip`); // 指定下载文件的名称

        // 触发下载
        document.body.appendChild(link);
        downloading.value = false
        link.click();
        // 释放 URL 对象
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
    } catch (error) {
        console.error('下载 ZIP 文件时出错:', error);
    }
}


</script>
<style lang="scss" scoped>
#map-container {
    width: 100%;
    height: 600px;
    cursor: pointer;
}

.preview-card-header {
    display: flex;
    justify-content: space-between;
}

.base-layer-card {
    background: none;

    .base-layer-header {
        display: flex;
        justify-content: space-between;

    }

    .base-layer-container {
        display: flex;
        justify-content: space-between;
    }

    .img-card {
        border: 2px solid hsla(210, 96%, 54%, 0);

        &:hover {
            border: 2px solid #1989fa;
        }
    }
}

.task-card {
    z-index: 100;
    position: absolute;
    height: 680px;
    background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));
    box-shadow: 0px 10px 19px 1px rgba(92, 99, 106, 0.38);
    border-radius: 3px;
    left: 34px;
    top: 120px;
    padding: 10px;

    .detial-con {
        padding: 10px;
        box-sizing: border-box;

        li {
            margin-bottom: 5px;
        }
    }

    overflow: scroll;
    overflow-x: hidden;
}

.custom-tree-node {
    width: 300px;

    .file-name {
        width: 190px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
}

.position_coordinate {
    color: #fff;
    position: absolute;
    font-size: 14px;
    bottom: 20px;
    right: 20px;
    z-index: 999;
    text-align: center;
    line-height: 30px;
    background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));
    padding: 5px 10px;
}
</style>
<style lang="scss">
.ol-popup {
    background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));

    .el-card__header {
        padding: 5px !important;

        .popup-header {
            display: flex;
            justify-content: space-between;
            font-size: 12px;
        }
    }

    .el-card__body {
        padding: 10px;
    }
}

.map-popover {
    padding: 0;
}

.preview-card {
    .el-card__header {
        padding: 10px !important;
    }

    .el-card__body {
        padding: 0;
    }
}

.base-layer-card {
    .el-card__header {
        padding: 5px !important;
    }

    .el-card__body {
        padding: 15px;
    }

    .el-card__footer {
        padding: 5px !important;
    }
}

.task-card {
    .el-form-item {
        margin-bottom: 5px !important;
    }

    .filter-container {

        .el-input__wrapper {
            box-shadow: 0 0 0 1px rgb(109, 194, 236) inset;
            background: rgba(34, 42, 51, 0.5);
            color: #D1E5FF;
        }

        color: #D1E5FF;
    }
}

.el-select__wrapper {
    box-shadow: 0 0 0 1px rgb(109, 194, 236) inset;
    background: rgba(34, 42, 51, 0.5);

    .el-table {
        --el-table-header-bg-color: #1b384d9c !important;
        --el-table-tr-bg-color: #2a57779c !important;
        --el-table-border-color: rgb(109, 194, 236);
        --el-table-row-hover-bg-color: #152b3a9c !important;

        tr {
            cursor: pointer;
        }
    }

    .page-container {
        --el-input-border-color: rgb(109, 194, 236) !important;

        .el-input__wrapper {
            box-shadow: 0 0 0 1px rgb(109, 194, 236)inset;
        }

        .el-select {
            --el-select-border-color-hover: rgb(109, 194, 236) !important;
        }
    }


    .el-tree-node {
        .el-tree-node__content {
            height: 30px !important;
        }

        .is-current {
            background: #0b283b;
        }
    }

    .el-tree-node__content:hover {
        background-color: rgb(53, 113, 156) !important;
    }

    .el-tree {
        --el-tree-node-hover-bg-color: rgba(42, 87, 119, 1) !important;

        .el-tree-node__expand-icon {
            font-size: 20px;
            color: rgba(51, 147, 208, 1);
        }

    }


}

.edit-container {
    z-index: 100;
    position: absolute;
    background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));
    box-shadow: 0px 10px 19px 1px rgba(92, 99, 106, 0.38);
    border-radius: 3px;
    right: 34px;
    top: 120px;
    width: 300px;

    .tool-header {
        padding: 0 5px 5px;
        border-bottom: 1px solid rgb(109, 194, 236);
        margin-bottom: 10px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .tool-body {
        .el-avatar {
            margin-right: 10px;
        }
    }

    .tool-footer {
        padding: 10px 5px;
        border-top: 1px solid rgb(109, 194, 236);
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .el-card__body {
        padding: 5px;

        .el-input__wrapper {
            box-shadow: 0 0 0 1px rgb(109, 194, 236) inset;
            background: rgba(34, 42, 51, 0.5);
            color: #D1E5FF;
        }
    }

}

.selected-card {
    z-index: 100;
    position: absolute;
    background: linear-gradient(0deg, #0b283b, rgba(21, 30, 40, 0.6));
    box-shadow: 0px 10px 19px 1px rgba(92, 99, 106, 0.38);
    border-radius: 3px;
    right: calc((100% - 300px)/2);
    top: 120px;
    width: 300px;
}
</style>